import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
// import router from './router'
import { message, Modal, notification } from 'ant-design-vue' /// es/notification
import { VueAxios } from './axios'
import { ACCESS_TOKEN, LOGIN_SYS } from '@/store/mutation-types'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? '/api/swpu/hd' : '/api', // api base_url
  timeout: 300000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)

    if (error.response.status === 403) {
      console.log('服务器403啦，要重新登录！')
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 500) {
      if (data.message.length > 0) {
        message.error(data.message)
      }
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
}, err)

/**
 * response interceptor
 * 所有请求统一返回
 */
service.interceptors.response.use(
  (response) => {
    if (response.request.responseType === 'blob') {
      return response
    }
    const resData = response.data
    const code = response.data.code
    if (!store.state.app.hasError) {
      if ([1011006, 1011007, 1011008, 1011009].includes(code)) {
        Modal.error({
          title: '提示：',
          content: resData.message,
          okText: '重新登录',
          onOk: () => {
            Vue.ls.remove(ACCESS_TOKEN)
            Vue.ls.remove(LOGIN_SYS)
            store.dispatch('SetHasError', false)
            window.location.reload()
          }
        })
        store.dispatch('SetHasError', true)
      }

      if ([1013002, 1016002, 1015002].includes(code)) {
        message.error(response.data.message)
        return Promise.reject(new Error(response.data.message))
      }
    }
    return resData
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response
      if (status === 401) {
        Modal.error({
          title: '未授权',
          content: '会话已过期，请重新登录。',
          okText: '重新登录',
          onOk: () => {
            Vue.ls.remove(ACCESS_TOKEN)
            Vue.ls.remove(LOGIN_SYS)
            store.dispatch('SetHasError', false)
            window.location.reload()
          }
        })
        store.dispatch('SetHasError', true)
      } else if (status === 500) {
        message.error(data.message || '服务器内部错误')
      } else {
        message.error(data.message || '请求错误')
      }
    } else {
      message.error('网络错误或请求超时')
    }
    return Promise.reject(error)
  }
)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
